package com.zhangyx.crawler.core.browser;

import org.apache.log4j.Logger;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BrowserUtil {
    private static Logger log = Logger.getLogger(BrowserUtil.class);

    private static ChromeDriver driverProxy;
    private static PhantomJSDriver phantomJSDriver;


    public static ChromeDriver createChromeDriver() {
       return createChromeDriver(null);
    }

    public static ChromeDriver createChromeDriver(ChromeOptions options) {
        String driverPath = System.getProperty("webdriver.chrome.driver");
        if (driverPath == null) {
            log.error("必须配置在System中配置webdriver.chrome.driver（chromedriver文件的位置），否则无法启动");
            return null;
        }
        if (options != null) {
            return new ChromeDriver(options);
        }
        return new ChromeDriver();
    }

    public static PhantomJSDriver getPhantom() {
        if (phantomJSDriver == null) {
            System.setProperty("phantomjs.binary.path", "D:\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
            DesiredCapabilities desiredCapabilities = DesiredCapabilities.phantomjs();
            //设置参数
            desiredCapabilities.setCapability("phantomjs.page.settings.userAgent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
            desiredCapabilities.setCapability("phantomjs.page.customHeaders.User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:50.0) Gecko/20100101 　　Firefox/50.0");
            phantomJSDriver = new PhantomJSDriver(desiredCapabilities);
        }
        return phantomJSDriver;
    }

    public static PhantomJSDriver getPhantomWithProxy() {
        if (phantomJSDriver == null) {
            System.setProperty("phantomjs.binary.path", "D:\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
            //设置参数
            ArrayList<String> cliArgsCap = new ArrayList<String>();
            cliArgsCap.add("--proxy=127.0.0.1:1080");
            // cliArgsCap.add("--proxy-auth=username:password");
            cliArgsCap.add("--proxy-type=http");
            DesiredCapabilities caps = new DesiredCapabilities();
            caps.setJavascriptEnabled(true);
            caps.setCapability("takesScreenshot", true);
            caps.setCapability("screen-resolution", "1280x1024");
            caps.setCapability("phantomjs.page.settings.userAgent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
            caps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliArgsCap);
            phantomJSDriver = new PhantomJSDriver(caps);
        }
        return phantomJSDriver;
    }

}

